using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Text;
using SmartCustomerService.Web.Models;

namespace SmartCustomerService.Web.Services;

public interface IAliyunBailianClient
{
    Task<string> ChatAsync(string message, string? systemPrompt = null, List<ChatMessage>? conversationHistory = null);
    Task<string> StreamChatAsync(string message, string? systemPrompt = null, List<ChatMessage>? conversationHistory = null);
}

public class AliyunBailianClient : IAliyunBailianClient
{
    private readonly HttpClient _httpClient;
    private readonly ILogger<AliyunBailianClient> _logger;
    private readonly string _apiKey;
    private readonly string _baseUrl;
    private readonly string _model;
    private readonly double _temperature;
    private readonly int _maxTokens;
    private readonly string _region;

    public AliyunBailianClient(HttpClient httpClient, IConfiguration configuration, ILogger<AliyunBailianClient> logger)
    {
        _httpClient = httpClient;
        _logger = logger;
        
        // 从配置文件读取阿里云百炼配置
        _apiKey = configuration["AliyunBailian:ApiKey"] ?? "sk-ae519eed6d8a4670ba036f6c98dc2f07";
        _baseUrl = configuration["AliyunBailian:BaseUrl"] ?? "https://dashscope.aliyuncs.com";
        _model = configuration["AliyunBailian:Model"] ?? "qwen-turbo";
        _temperature = double.TryParse(configuration["AliyunBailian:Temperature"], out var temp) ? temp : 0.7;
        _maxTokens = int.TryParse(configuration["AliyunBailian:MaxTokens"], out var tokens) ? tokens : 2000;
        _region = configuration["AliyunBailian:Region"] ?? "cn-hangzhou";
        
        // HttpClient 基础设置
        _httpClient.Timeout = TimeSpan.FromSeconds(30);
        if (_httpClient.DefaultRequestHeaders.AcceptEncoding.Count == 0)
        {
            _httpClient.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
        }
        // 默认请求头
        _httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {_apiKey}");
        _httpClient.DefaultRequestHeaders.Add("User-Agent", "SmartCustomerService/1.0");
        
        _logger.LogInformation("Aliyun Bailian configured. BaseUrl={BaseUrl}, Model={Model}, ApiKey={ApiKey}", _baseUrl, _model, _apiKey.Substring(0, 10) + "...");
    }

    private async Task<HttpResponseMessage> PostWithRetryAsync(string url, HttpContent content, int maxRetry = 2)
    {
        for (int attempt = 0; ; attempt++)
        {
            try
            {
                var resp = await _httpClient.PostAsync(url, content);
                if ((int)resp.StatusCode >= 500 && attempt < maxRetry)
                {
                    await Task.Delay(300 * (attempt + 1));
                    continue;
                }
                return resp;
            }
            catch (TaskCanceledException) when (attempt < maxRetry)
            {
                await Task.Delay(300 * (attempt + 1));
                continue;
            }
        }
    }

    public async Task<string> ChatAsync(string message, string? systemPrompt = null, List<ChatMessage>? conversationHistory = null)
    {
        try
        {
            var request = BuildChatRequest(message, systemPrompt, conversationHistory);
            var json = JsonConvert.SerializeObject(request);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            _logger.LogInformation("Calling Aliyun Bailian API for message: {Message}", message);
            _logger.LogInformation("Request URL: {Url}", $"{_baseUrl}/api/v1/services/aigc/text-generation/generation");
            _logger.LogInformation("Request JSON: {Json}", json);

            var response = await PostWithRetryAsync($"{_baseUrl}/api/v1/services/aigc/text-generation/generation", content);
            var responseContent = await response.Content.ReadAsStringAsync();

            _logger.LogInformation("Response Status: {Status}", response.StatusCode);
            _logger.LogInformation("Response Content: {Content}", responseContent);

            if (!response.IsSuccessStatusCode)
            {
                _logger.LogError("Aliyun Bailian API returned error: {Status} - {Content}", response.StatusCode, responseContent);
                return $"[API错误] 调用阿里云百炼模型失败: {response.StatusCode} - {responseContent}";
            }

            // 尝试解析响应
            AliyunBailianResponse? apiResponse = null;
            try
            {
                apiResponse = JsonConvert.DeserializeObject<AliyunBailianResponse>(responseContent);
            }
            catch (JsonException ex)
            {
                _logger.LogError(ex, "Failed to parse API response: {Content}", responseContent);
                return $"[解析错误] AI服务返回格式异常: {ex.Message}";
            }

            // 兼容多种返回格式
            string? aiResponse = null;
            aiResponse = apiResponse?.Output?.Choices?.FirstOrDefault()?.Message?.Content;
            if (string.IsNullOrWhiteSpace(aiResponse))
            {
                // 有些返回结构为 choices[0].text
                aiResponse = apiResponse?.Output?.Choices?.FirstOrDefault()?.Text;
            }
            if (string.IsNullOrWhiteSpace(aiResponse))
            {
                // 有些返回结构为 output.text
                aiResponse = apiResponse?.Output?.Text;
            }
            if (string.IsNullOrWhiteSpace(aiResponse))
            {
                // 兜底尝试从简单 JSON 中提取
                try
                {
                    var root = JsonConvert.DeserializeObject<dynamic>(responseContent);
                    aiResponse = (string?)root?.output?.text;
                    if (string.IsNullOrWhiteSpace(aiResponse))
                    {
                        aiResponse = (string?)root?.output?.choices?[0]?.text;
                    }
                    if (string.IsNullOrWhiteSpace(aiResponse))
                    {
                        aiResponse = (string?)root?.output?.choices?[0]?.message?.content;
                    }
                }
                catch
                {
                    // ignore
                }
            }

            if (string.IsNullOrWhiteSpace(aiResponse))
            {
                _logger.LogWarning("Aliyun Bailian API returned empty response: {Content}", responseContent);
                return "抱歉，我暂时无法理解您的问题，请重新描述一下。";
            }

            _logger.LogInformation("Received response from Aliyun Bailian: {Response}", aiResponse);
            return aiResponse;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error calling Aliyun Bailian API");
            return $"[系统错误] 调用AI服务时发生错误，请稍后重试。错误详情: {ex.Message}";
        }
    }

    public async Task<string> StreamChatAsync(string message, string? systemPrompt = null, List<ChatMessage>? conversationHistory = null)
    {
        try
        {
            var request = BuildChatRequest(message, systemPrompt, conversationHistory);
            request.Stream = true; // 启用流式响应
            
            var json = JsonConvert.SerializeObject(request);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            _logger.LogInformation("Calling Aliyun Bailian API with streaming for message: {Message}", message);

            // 仅在流式请求时添加 SSE 头
            using var httpRequest = new HttpRequestMessage(HttpMethod.Post, $"{_baseUrl}/api/v1/services/aigc/text-generation/generation")
            {
                Content = content
            };
            httpRequest.Headers.Add("X-DashScope-SSE", "enable");

            var response = await _httpClient.SendAsync(httpRequest);
            
            if (!response.IsSuccessStatusCode)
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                _logger.LogError("Aliyun Bailian API streaming error: {Status} - {Content}", response.StatusCode, errorContent);
                return $"[API错误] 调用阿里云百炼模型失败: {response.StatusCode}";
            }

            // 处理流式响应
            var responseContent = await response.Content.ReadAsStringAsync();
            return ProcessStreamResponse(responseContent);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error calling Aliyun Bailian API with streaming");
            return "[系统错误] 调用AI服务时发生错误，请稍后重试。";
        }
    }

    private AliyunBailianRequest BuildChatRequest(string message, string? systemPrompt, List<ChatMessage>? conversationHistory)
    {
        var messages = new List<AliyunBailianMessage>();

        // 添加系统提示词
        if (!string.IsNullOrEmpty(systemPrompt))
        {
            messages.Add(new AliyunBailianMessage
            {
                Role = "system",
                Content = systemPrompt
            });
        }

        // 添加对话历史
        if (conversationHistory != null && conversationHistory.Any())
        {
            foreach (var history in conversationHistory.TakeLast(10)) // 限制历史记录数量
            {
                messages.Add(new AliyunBailianMessage
                {
                    Role = history.IsUser ? "user" : "assistant",
                    Content = history.Content
                });
            }
        }

        // 添加当前用户消息
        messages.Add(new AliyunBailianMessage
        {
            Role = "user",
            Content = message
        });

        return new AliyunBailianRequest
        {
            Model = _model,
            Input = new AliyunBailianInput { Messages = messages },
            Parameters = new AliyunBailianParameters
            {
                Temperature = _temperature,
                MaxTokens = _maxTokens
            },
            Stream = false
        };
    }

    private string ProcessStreamResponse(string streamContent)
    {
        try
        {
            var sb = new StringBuilder();
            var lines = streamContent.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            
            foreach (var line in lines)
            {
                if (line.StartsWith("data: "))
                {
                    var data = line.Substring(6);
                    if (data == "[DONE]") break;
                    
                    try
                    {
                        var chunk = JsonConvert.DeserializeObject<AliyunBailianStreamResponse>(data);
                        var content = chunk?.Output?.Choices?.FirstOrDefault()?.Delta?.Content;
                        if (!string.IsNullOrEmpty(content))
                        {
                            sb.Append(content);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning(ex, "Failed to parse stream chunk: {Data}", data);
                    }
                }
            }
            
            var result = sb.ToString();
            return string.IsNullOrEmpty(result) ? "抱歉，我暂时无法理解您的问题，请重新描述一下。" : result;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error processing stream response");
            return "抱歉，处理AI响应时发生错误，请稍后重试。";
        }
    }
}

// 阿里云百炼API请求模型
public class AliyunBailianRequest
{
    [JsonProperty("model")]
    public string Model { get; set; } = string.Empty;

    [JsonProperty("input")]
    public AliyunBailianInput Input { get; set; } = new();

    [JsonProperty("parameters")]
    public AliyunBailianParameters Parameters { get; set; } = new();

    [JsonProperty("stream")]
    public bool Stream { get; set; } = false;
}

public class AliyunBailianInput
{
    [JsonProperty("messages")]
    public List<AliyunBailianMessage> Messages { get; set; } = new();
}

public class AliyunBailianParameters
{
    [JsonProperty("temperature")]
    public double Temperature { get; set; } = 0.7;

    [JsonProperty("max_tokens")]
    public int MaxTokens { get; set; } = 2000;
}

public class AliyunBailianMessage
{
    [JsonProperty("role")]
    public string Role { get; set; } = string.Empty;

    [JsonProperty("content")]
    public string Content { get; set; } = string.Empty;
}

// 阿里云百炼API响应模型
public class AliyunBailianResponse
{
    [JsonProperty("output")]
    public AliyunBailianOutput? Output { get; set; }

    [JsonProperty("usage")]
    public AliyunBailianUsage? Usage { get; set; }
}

public class AliyunBailianOutput
{
    [JsonProperty("choices")]
    public List<AliyunBailianChoice>? Choices { get; set; }

    // 兼容直返 text 的结构
    [JsonProperty("text")]
    public string? Text { get; set; }
}

public class AliyunBailianChoice
{
    [JsonProperty("message")]
    public AliyunBailianMessage? Message { get; set; }

    // 兼容 choices[].text 的结构
    [JsonProperty("text")]
    public string? Text { get; set; }
}

public class AliyunBailianUsage
{
    [JsonProperty("total_tokens")]
    public int TotalTokens { get; set; }

    [JsonProperty("input_tokens")]
    public int InputTokens { get; set; }

    [JsonProperty("output_tokens")]
    public int OutputTokens { get; set; }
}

// 流式响应模型
public class AliyunBailianStreamResponse
{
    [JsonProperty("output")]
    public AliyunBailianStreamOutput? Output { get; set; }
}

public class AliyunBailianStreamOutput
{
    [JsonProperty("choices")]
    public List<AliyunBailianStreamChoice>? Choices { get; set; }
}

public class AliyunBailianStreamChoice
{
    [JsonProperty("delta")]
    public AliyunBailianMessage? Delta { get; set; }
}